package com.glela.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.glela.constant.BizConstant;
import com.glela.goods.model.request.RequestBrandModel;
import com.glela.goods.model.vo.CategorySelectVo;
import com.glela.goods.model.vo.ResponseStorePageModel;
import com.glela.goods.model.vo.StoreResponse;
import com.glela.goods.model.vo.brand.BrandHotVo;
import com.glela.goods.model.vo.brand.BrandUserEnjoyVo;
import com.glela.goods.model.vo.brand.BrandVo;
import com.glela.goods.model.vo.brand.UserEnjoyBrandsAndInvitationNum;
import com.glela.goods.service.BrandService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

@RequestMapping("/brand")
@RestController
public class BrandController {
	private static Logger logger = LoggerFactory.getLogger(BrandController.class);

	@Autowired
	private BrandService brandService;
	@Autowired
	private UserService userService;

	/**
	 * 首页人气品牌展示接口
	 * 
	 * @author 卫耀华
	 */
	@RequestMapping(value = "/hotBrand", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> hotBrand() {
		try {
			List<BrandHotVo> list = brandService.getHotBrand();
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	@RequestMapping(value = "/testHotBrand", method = RequestMethod.GET)
	public ResponseEntity<?> testHotBrand() {
		try {
			List<BrandHotVo> list = brandService.getHotBrand();
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 用户喜欢的品牌
	 * 
	 * @author 卫耀华
	 */
	@RequestMapping(value = "/userEnjoyBrands", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> userEnjoyBrands(@RequestBody RequestBrandModel brandModel) {
		try {
			// 输入参数校验，判断是否允许为空
			if (ParameterUtils.validParams(brandModel.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			User user = userService.getUser(brandModel.getUserId());
			if (null == user) {
				// 此用户不存在
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			List<BrandUserEnjoyVo> list = brandService.getBrandsUserEnjoy(brandModel.getUserId());
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 获取所有品牌列表
	 * 
	 * @author 卫耀华
	 * @date 2016-10-13
	 * @return
	 */
	@RequestMapping(value = "/getAllBrands", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getAllBrands() {
		try {
			// 获取所有品牌
			List<BrandVo> voList = brandService.getAllBrands();
			Set<String> firstKeySet = new LinkedHashSet<>();
			Map<String, List<BrandVo>> map = new HashMap<String, List<BrandVo>>();
			if (voList != null && voList.size() > 0) {
				for (BrandVo vo : voList) {
					if (StringUtils.isNotEmpty(vo.getFirstChar())) {
						firstKeySet.add(vo.getFirstChar().toUpperCase());
					}
				}
				for (String str : firstKeySet) {
					List<BrandVo> brandList = new ArrayList<BrandVo>();
					for (BrandVo vo : voList) {
						if (vo.getFirstChar().toUpperCase().equals(str)) {
							brandList.add(vo);
							map.put(str, brandList);
						}
					}
				}
			}
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取所有品牌发生异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 用户点击我喜欢这个品牌
	 * 
	 * @author 卫耀华
	 * @date 2016-10-13
	 * @return
	 */
	@RequestMapping(value = "/userEnjoyThisBrand", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> userEnjoyThisBrand(@RequestBody RequestBrandModel brandModel) {
		try {
			// 输入参数校验，判断是否允许为空
			if (ParameterUtils.validParams(brandModel.getBrandId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (BizConstant.ENJOY_TYPE_Y != brandModel.getType() && BizConstant.ENJOY_TYPE_N != brandModel.getType()) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			if (brandModel.getUserId() != 0L) {
				User user = userService.getUser(brandModel.getUserId());
				if (null == user) {
					// 此用户不存在
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
				}
			}			
			// 1、先判断该用户有没有关注过这个品牌
			int count = brandService.countBrandsByUserIdAndBrandId(brandModel.getUserId(), brandModel.getBrandId());
			if (BizConstant.ENJOY_TYPE_Y == brandModel.getType()) {
				if (count > 0) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20124), HttpStatus.OK);
				}
				// 2、保存用户喜欢这个品牌
				brandService.saveBrandUserEnjoy(brandModel.getUserId(), brandModel.getBrandId());
				// 3、品牌用户喜欢数量加1
				brandService.updateLikeCountById(brandModel.getBrandId());
			} else if (BizConstant.ENJOY_TYPE_N == brandModel.getType()) {
				if (count == 0) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20132), HttpStatus.OK);
				}
				// 2、用户取消喜欢喜欢这个品牌
				brandService.deleteBrandUserEnjoyByUserIdAndBrandId(brandModel.getUserId(), brandModel.getBrandId());
				// 3、品牌用户喜欢数量减去1
				brandService.updateLikeNumSubtract1ByBrandId(brandModel.getBrandId());
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 品牌详情页基本信息
	 * 
	 * @author 卫耀华
	 * @date 2016-10-13
	 */
	@RequestMapping(value = "/brandBaseInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> brandBaseInfo(@RequestBody RequestBrandModel brandModel) {
		try {
			BrandVo vo = brandService.selectBrandById(brandModel.getBrandId(), brandModel.getUserId());
			if (null == vo) {
				// 无此品牌
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20408), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 品牌详情页店铺列表(欲购专用)
	 * 
	 * @author 卫耀华
	 * @date 2016-10-13
	 */
	@RequestMapping(value = "/brandStoreList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> brandStoreList(@RequestBody RequestBrandModel brandModel) {
		try {
			if (ParameterUtils.validParams(brandModel.getBrandId(), brandModel.getLat(), brandModel.getLon())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<StoreResponse> volist = brandService.getAllStoreListByBrandId(brandModel.getBrandId(),
					brandModel.getLat(), brandModel.getLon(), brandModel.getStartIndex(), brandModel.getPageSize());
			int count = brandService.countStoreNumByBrandId(brandModel.getBrandId());
			ResponseStorePageModel pageModel = new ResponseStorePageModel(count, volist);

			return new ResponseEntity<>(new ResponseResultModel<ResponsePageModel<StoreResponse>>(pageModel),
					HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 首页精选分类
	 * 
	 * @author 卫耀华
	 */
	@RequestMapping(value = "/categorySelect", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> categorySelect() {
		try {
			List<CategorySelectVo> list = brandService.getCategorySelect();
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 品牌详情页店铺列表(校妆专用)
	 * 
	 * @author 卫耀华
	 * @date 2016-10-13
	 */
	@RequestMapping(value = "/brandStores", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> brandStores(@RequestBody RequestBrandModel brandModel) {
		try {
			if (ParameterUtils.validParams(brandModel.getBrandId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<StoreResponse> volist = brandService.getStoresByBrandId(brandModel.getBrandId(),
					brandModel.getStartIndex(), brandModel.getPageSize());
			int count = brandService.countStoreNumByBrandId(brandModel.getBrandId());
			ResponseStorePageModel pageModel = new ResponseStorePageModel(count, volist);

			return new ResponseEntity<>(new ResponseResultModel<ResponsePageModel<StoreResponse>>(pageModel),
					HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询喜欢的品牌数和邀请的小伙伴数量
	 * 
	 * @author 卫耀华
	 * @date 2016-10-21
	 * @param brandModel
	 * @return
	 */
	@RequestMapping(value = "/enjoybrandsNumAndInvitationNum", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> enjoybrandsNumAndInvitationNum(@RequestBody RequestBrandModel brandModel) {
		try {
			if (brandModel.getUserId() == 0) {
				return new ResponseEntity<>(new ResponseResultModel<>(new UserEnjoyBrandsAndInvitationNum()),
						HttpStatus.OK);
			}
			User user = userService.getUser(brandModel.getUserId());
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			int invitationNum = userService.selectInvitationNumByUserId(user.getId());
			List<BrandUserEnjoyVo> voList = brandService.getBrandsUserEnjoy(brandModel.getUserId());
			UserEnjoyBrandsAndInvitationNum model = new UserEnjoyBrandsAndInvitationNum();
			model.setUserId(user.getId());
			model.setEnjoyBrandNum(voList.size());
			model.setInvitationNum(invitationNum);
			model.setMoney(userService.selectUserMoney(user.getId()));
			return new ResponseEntity<>(new ResponseResultModel<>(model), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
}
